<?php
namespace App\Http\Controllers\Manage\Manage;

use App\Http\Controllers\Manage\CommonController;
use App\Model\Manage\ManageRole;
use App\Model\Manage\ManageMapRole;
use Hash;

class ManageRuleController extends CommonController
{

    public function index()
    {
        $id = $this->request->input('id');
        # 读取当前管理员拥有的角色
        $roleValue = ManageMapRole::where('manage_id', $id)->lists('role_id')->implode(',');
        $role = array();
        $result = ManageRole::get();
        foreach ($result as $key => $val) {
            $role[$val->id] = $val->name;
        }
        # 表单元素配置
        $param = [
            'role' => [
                'type' => 'checkbox',
                'col' => '12',
                'name' => '角色名称',
                'range' => $role,
                'value' => $roleValue,
            ],
        ];
        $form = $this->form($param);
        return view('manage.lib.form')
            ->with('form', $form)
            ->with('form_url', route('manage.user.rule.resource.store', ['id' => $id]))
            ->with('form_method', 'POST')
            ->with('form_title', '权限设置');
        # 生成表单元素
        //$element = FormElement::display($param);
        # 渲染视图
//        return view('manage.lib.form')
//            ->with('element', $element);
    }

    public function store()
    {
        $id = $this->request->input('id');
        $role = $this->request->input('role');
        if ($role) {
            # 查询已有角色关联记录
            $map = ManageMapRole::where('manage_id', $id)->lists('role_id')->toArray();
            # 过滤已有的角色关联数据，并获取需要删除的角色关联数据
            # 需要添加是数据
            $add = array_diff($role, $map);
            # 执行添加记录
            $data = array();
            foreach ($add as $val) {
                $data[] = [
                    'manage_id' => $id,
                    'role_id' => $val
                ];
            }
            ManageMapRole::insert($data);
            # 需要删除的数据
            $del = array_diff($map, $role);
            # 执行删除记录
            ManageMapRole::where('manage_id', $id)->whereIn('role_id', $del)->delete();
            return redirect()->back()->with('success', '管理员权限修改成功!');
        }
        return redirect()->back()->with('error', '管理员权限修改失败!');
    }
}
